package com.office.workflow.controller;

import com.office.common.annotation.Log;
import com.office.common.core.controller.BaseController;
import com.office.common.core.domain.AjaxResult;
import com.office.common.core.page.TableDataInfo;
import com.office.common.enums.BusinessType;
import com.office.common.utils.poi.ExcelUtil;
import com.office.workflow.domain.Workflow;
import com.office.workflow.domain.WorkflowInstance;
import com.office.workflow.service.WorkflowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 工作流Controller
 * 
 * @author 数字牧马人
 */
@RestController
@RequestMapping("/system/workflow")
public class WorkflowController extends BaseController
{
    @Autowired
    private WorkflowService workflowService;

    /**
     * 查询工作流列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Workflow workflow)
    {
        startPage();
        List<Workflow> list = workflowService.selectWorkflowList(workflow);
        return getDataTable(list);
    }

    /**
     * 导出工作流列表
     */
    @Log(title = "工作流", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Workflow workflow)
    {
        List<Workflow> list = workflowService.selectWorkflowList(workflow);
        ExcelUtil<Workflow> util = new ExcelUtil<Workflow>(Workflow.class);
        util.exportExcel(response, list, "工作流数据");
    }

    /**
     * 获取工作流详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(workflowService.selectWorkflowById(id));
    }

    /**
     * 新增工作流
     */
    @Log(title = "工作流", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Workflow workflow)
    {
        return toAjax(workflowService.insertWorkflow(workflow));
    }

    /**
     * 修改工作流
     */
    @Log(title = "工作流", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Workflow workflow)
    {
        return toAjax(workflowService.updateWorkflow(workflow));
    }

    /**
     * 删除工作流
     */
    @Log(title = "工作流", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(workflowService.deleteWorkflowByIds(ids));
    }

    /**
     * 获取工作流设计数据
     */
    @GetMapping(value = "/design/{id}")
    public AjaxResult getDesign(@PathVariable("id") Long id)
    {
        return success(workflowService.getWorkflowDesign(id));
    }

    /**
     * 保存工作流设计
     */
    @Log(title = "保存工作流设计", businessType = BusinessType.UPDATE)
    @PostMapping("/saveDesign")
    public AjaxResult saveDesign(@RequestBody Workflow workflow)
    {
        return toAjax(workflowService.saveWorkflowDesign(workflow));
    }

    /**
     * 执行工作流
     */
    @Log(title = "执行工作流", businessType = BusinessType.OTHER)
    @PostMapping("/execute/{id}")
    public AjaxResult execute(@PathVariable("id") Long id, @RequestBody Map<String, Object> inputParams)
    {
        Map<String, Object> result = workflowService.executeWorkflow(id, inputParams);
        if ((Boolean) result.get("success")) {
            return success(result);
        } else {
            return error((String) result.get("error"));
        }
    }

    /**
     * 查询工作流执行实例列表
     */
    @GetMapping("/instance/list")
    public TableDataInfo instanceList(WorkflowInstance instance)
    {
        startPage();
        List<WorkflowInstance> list = workflowService.selectWorkflowInstanceList(instance);
        return getDataTable(list);
    }

    /**
     * 获取工作流执行实例详细信息
     */
    @GetMapping(value = "/instance/{id}")
    public AjaxResult getInstanceInfo(@PathVariable("id") Long id)
    {
        return success(workflowService.selectWorkflowInstanceById(id));
    }

    /**
     * 删除工作流执行实例
     */
    @Log(title = "工作流执行实例", businessType = BusinessType.DELETE)
    @DeleteMapping("/instance/{ids}")
    public AjaxResult removeInstance(@PathVariable Long[] ids)
    {
        return toAjax(workflowService.deleteWorkflowInstanceByIds(ids));
    }

    /**
     * 导入工作流
     */
    @Log(title = "导入工作流", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importWorkflow(@RequestParam("file") MultipartFile file,
                                     @RequestParam("name") String name,
                                     @RequestParam(value = "desc", required = false) String desc) throws IOException
    {
        try {
            String json = new String(file.getBytes(), StandardCharsets.UTF_8);
            // 解析JSON为Map
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> workflowData = objectMapper.readValue(json, Map.class);
            // 覆盖名称和描述
            workflowData.put("name", name);
            if (desc != null) {
                workflowData.put("desc", desc);
            }
            int result = workflowService.importWorkflow(workflowData);
            if (result > 0) {
                return success("导入成功");
            } else {
                return error("导入失败：未能写入数据库");
            }
        } catch (Exception e) {
            return error("导入失败: " + e.getMessage());
        }
    }

    /**
     * 导出工作流
     */
    @GetMapping("/export/{id}")
    public AjaxResult exportWorkflow(@PathVariable("id") Long id)
    {
        try {
            Map<String, Object> exportData = workflowService.exportWorkflow(id);
            return success(exportData);
        } catch (Exception e) {
            return error("导出失败: " + e.getMessage());
        }
    }

    /**
     * 获取工作流统计信息
     */
    @GetMapping("/statistics")
    public AjaxResult getStatistics()
    {
        try {
            // 统计工作流总数
            Workflow workflow = new Workflow();
            List<Workflow> workflows = workflowService.selectWorkflowList(workflow);
            int totalWorkflows = workflows.size();
            
            // 统计执行实例总数
            WorkflowInstance instance = new WorkflowInstance();
            List<WorkflowInstance> instances = workflowService.selectWorkflowInstanceList(instance);
            int totalExecutions = instances.size();
            
            // 统计成功执行次数
            long successExecutions = instances.stream()
                .filter(i -> "1".equals(i.getStatus()))
                .count();
            
            // 计算成功率
            String successRate = totalExecutions > 0 ? 
                String.format("%.1f%%", (double) successExecutions / totalExecutions * 100) : "0%";
            
            Map<String, Object> statistics = Map.of(
                "totalWorkflows", totalWorkflows,
                "totalExecutions", totalExecutions,
                "successExecutions", successExecutions,
                "successRate", successRate
            );
            return success(statistics);
        } catch (Exception e) {
            return error("获取统计信息失败: " + e.getMessage());
        }
    }
} 